<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>let-实践案例</title>
</head>

<style>
  .page-header {
    padding-bottom: 10px;
    border-bottom: 1px solid #ddd;
  }
  .item {
    display: inline-block;
    width: 200px;
    height: 200px;
    margin: 10px;
    border: 1px solid green;
  }
</style>

<body>
  <div class="container">
    <h2 class="page-header">点击切换颜色</h2>
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
  </div>
</body>
<script>
  // 获取div元素对象
  var item = document.getElementsByClassName("item");

  /* 
    for(var i=0; i<item.length; i++) {
      (function(i) {
        item[i].onclick = function() {
          // this.style.backgroundColor = "green";
          item[i].style.backgroundColor = "green";
        }
      })(i)
    }

    实际上 i 执行以下步骤
    {
      i = 0
    }

    {
      i = 1
    }

    {
      i = 2
    }

    console.log(i)  // 外层是3
  */

  // let 之后 i 就被限定了块级作用域
  for(let i=0; i<item.length; i++) {
    item[i].onclick = function() {
      item[i].style.backgroundColor = "green";
    }
  }

  // 实际上 i 执行以下步骤
  /* 
    {
      let i = 0
      item[i].onclick = function() {
        item[i].style.backgroundColor = "green";
      }
    }

    {
      let i = 1
      item[i].onclick = function() {
        item[i].style.backgroundColor = "green";
      }
    }

    {
      let i = 2
      item[i].onclick = function() {
        item[i].style.backgroundColor = "green";
      }
    } 
  */
  
</script>
</html>